import React, { useState, useCallback, useEffect } from 'react'
import {
  Redirect,
  useHistory,
  useRouteMatch
} from 'react-router-dom'

import '@/assets/styles/animate.css'

import {
  CategoryWrap,
  NavList
} from './StyledCategory'

import Classify from './Classify'
import Material from './Material'

import Search from '@/components/search/Search'

import {get} from '@/utils/http'

function Category() {
  let [navDir, setNavDir] = useState('left')
  let [datalist, setDatalist] = useState(null) 
  
  const match = useRouteMatch()
  const history = useHistory()

  const handleNavClick = useCallback(
    (dir) => {
      const type = dir === 'left' ? 'classify' : 'material'
      return () => {
        setNavDir(dir)
        history.push({
          pathname: `${match.url}/${type}`, 
          state: {to: type}
        })
      }
    },
    [history, match]
  )

  useEffect(() => {
    (async ()=>{
      let result = await get({
        url: '/api/category'
        // url: '/mock/cookbook-category.json'
      })
      setDatalist(result.data.data)
    })()
  }, [])

  const url = match.url

  return (
    <CategoryWrap>
      <nav>
        <NavList
          color="#fff"
          radius={0.15}
        >
          <li
            className={navDir === 'left' ? 'active' : ''}
            onClick={handleNavClick('left')}
          >分类</li>
          <li
            className={navDir === 'right' ? 'active' : ''}
            onClick={handleNavClick('right')}
          >食材</li>
          <li className={`slider ${navDir === 'left' ? '' : 'right'}`}></li>
        </NavList>
      </nav>
      <Search
        bgInnerColor="#efefef"
        bgOuterColor="#fff"
        hasBorder={false}
      ></Search>
      <div className="menu">
        {
          datalist && <Classify list={datalist.category} path={`${url}/classify`}></Classify>
        }
        {
          datalist && <Material list={datalist.material} path={`${url}/material`}></Material>
        }
        <Redirect from={url} to={`${url}/classify`}></Redirect>
      </div>
    </CategoryWrap>
  )
}

export default Category
